package com.icoolkj.security.springmvc.config;


import jakarta.servlet.http.HttpSession;
import org.springframework.cglib.proxy.NoOp;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author icoolkj
 * @version 1.0
 * @description 安全配置
 * @createDate 2025/02/07 09:25
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    // 定义用户信息服务（相当于查询用户信息）
    @Bean
    public UserDetailsService userDetailsService() {
        // 基于内存
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
        manager.createUser(User.withUsername("lisi").password("678").authorities("p2").build());
        return manager;
    }

    // 定义密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    // 配置安全拦截机制 （最重要）
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorizeRequests -> authorizeRequests
                                .requestMatchers("/r/r1").hasAuthority("p1")
                                .requestMatchers("/r/r2").hasAuthority("p2")
                                .requestMatchers("/r/**").authenticated() // 所有 /r/** 的请求必须认证通过
                                .anyRequest().permitAll()  // 除了 /r/**，其它请求可以访问
                                )
                                .formLogin(formLogin -> formLogin // 允许表单登录
                                    .successForwardUrl("/login-success") // 自定义登录成功的页面地址
                                )
                                .logout(logout -> logout.permitAll())
                                .csrf(csrf -> csrf.disable()); // 暂时禁用 CSRF 防护，实际应用中可根据需求配置
        return http.build();
    }




}
